package com.jh.cloud.bus.controller;

import com.jh.cloud.bus.entity.event.RemoteAppEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 远程事件控制器
 */
@RestController
public class RemoteAppEventSendController implements ApplicationEventPublisherAware {

    private ApplicationEventPublisher publisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }

    @GetMapping("/send/remote/event")
    public String sendEvent(@RequestParam String message) {
        publisher.publishEvent(message);
        return "Sent";
    }

    @GetMapping("/send/remote/event/{appName}")
    public String sendAppCluster(@PathVariable String appName,
                                 @RequestBody Map data) {

        RemoteAppEvent remoteAppEvent = new RemoteAppEvent(data, appName, Boolean.TRUE);
        // 给当前上下文发送事件（自己）
        publisher.publishEvent(remoteAppEvent);

        return "Sent To Cluster";
    }

    @GetMapping("/send/remote/event/{appName}/{ip}/{port}")
    public String sendAppInstance(@PathVariable String appName,
                                  @PathVariable String ip,
                                  @PathVariable Integer port,
                                  @RequestBody Object data) {

        RemoteAppEvent remoteAppEvent = new RemoteAppEvent(data, appName, Boolean.FALSE);
        // 给当前上下文发送事件（自己）
        publisher.publishEvent(remoteAppEvent);

        return "Sent To Instance";
    }

}
